<!--
  智慧社区管理系统 - 表读数录入弹窗组件
  @author Wu.Liang
  @date 2024-12-21
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="表读数录入"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="meter-reading-content">
      <!-- 录入方式选择 -->
      <el-card class="input-method-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>录入方式</span>
          </div>
        </template>
        <el-radio-group v-model="inputMethod" @change="handleInputMethodChange">
                      <el-radio value="SINGLE">单个录入</el-radio>
            <el-radio value="BATCH">批量录入</el-radio>
        </el-radio-group>
      </el-card>

      <!-- 单个录入 -->
      <div v-if="inputMethod === 'SINGLE'" class="single-input">
        <el-form
          ref="singleFormRef"
          :model="singleForm"
          :rules="singleRules"
          label-width="120px"
        >
          <el-form-item label="选择社区" prop="communityId">
            <el-select
              v-model="singleForm.communityId"
              placeholder="请选择社区"
              style="width: 100%"
              @change="handleCommunityChange"
            >
              <el-option
                v-for="item in communityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择楼栋" prop="buildingId">
            <el-select
              v-model="singleForm.buildingId"
              placeholder="请选择楼栋"
              style="width: 100%"
              @change="handleBuildingChange"
            >
              <el-option
                v-for="item in buildingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="选择房户" prop="householdId">
            <el-select
              v-model="singleForm.householdId"
              placeholder="请选择房户"
              style="width: 100%"
              @change="handleHouseholdChange"
            >
              <el-option
                v-for="item in householdList"
                :key="item.id"
                :label="item.roomNumber"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="表类型" prop="meterType">
            <el-radio-group v-model="singleForm.meterType">
              <el-radio value="WATER">水表</el-radio>
              <el-radio value="ELECTRICITY">电表</el-radio>
              <el-radio value="GAS">燃气表</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="表号" prop="meterNumber">
            <el-input
              v-model="singleForm.meterNumber"
              placeholder="请输入表号"
            />
          </el-form-item>

          <el-form-item label="本次读数" prop="currentReading">
            <el-input-number
              v-model="singleForm.currentReading"
              :min="0"
              :precision="2"
              :step="0.01"
              placeholder="请输入本次读数"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="上次读数">
            <el-input-number
              v-model="singleForm.previousReading"
              :min="0"
              :precision="2"
              :step="0.01"
              placeholder="上次读数（可选）"
              style="width: 100%"
              disabled
            />
          </el-form-item>

          <el-form-item label="用量">
            <el-input-number
              v-model="singleForm.usage"
              :min="0"
              :precision="2"
              :step="0.01"
              placeholder="自动计算"
              style="width: 100%"
              disabled
            />
          </el-form-item>

          <el-form-item label="读数日期" prop="readingDate">
            <el-date-picker
              v-model="singleForm.readingDate"
              type="date"
              placeholder="请选择读数日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="singleForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（可选）"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量录入 -->
      <div v-else class="batch-input">
        <el-form
          ref="batchFormRef"
          :model="batchForm"
          :rules="batchRules"
          label-width="120px"
        >
          <el-form-item label="选择社区" prop="communityId">
            <el-select
              v-model="batchForm.communityId"
              placeholder="请选择社区"
              style="width: 100%"
              @change="handleBatchCommunityChange"
            >
              <el-option
                v-for="item in communityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="表类型" prop="meterType">
            <el-radio-group v-model="batchForm.meterType">
              <el-radio value="WATER">水表</el-radio>
              <el-radio value="ELECTRICITY">电表</el-radio>
              <el-radio value="GAS">燃气表</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="读数日期" prop="readingDate">
            <el-date-picker
              v-model="batchForm.readingDate"
              type="date"
              placeholder="请选择读数日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="批量数据" prop="readings">
            <div class="batch-data-section">
              <div class="batch-header">
                <span>房户列表</span>
                <el-button type="primary" size="small" @click="loadHouseholdList">
                  加载房户列表
                </el-button>
              </div>
              <el-table
                :data="batchForm.readings"
                border
                style="width: 100%"
                max-height="300"
              >
                <el-table-column prop="roomNumber" label="房号" width="100" />
                <el-table-column prop="householdName" label="业主" width="100" />
                <el-table-column prop="meterNumber" label="表号" width="120">
                  <template #default="{ row }">
                    <el-input
                      v-model="row.meterNumber"
                      placeholder="请输入表号"
                      size="small"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="currentReading" label="本次读数" width="120">
                  <template #default="{ row }">
                    <el-input-number
                      v-model="row.currentReading"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                      placeholder="读数"
                      size="small"
                      style="width: 100%"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="previousReading" label="上次读数" width="120">
                  <template #default="{ row }">
                    <el-input-number
                      v-model="row.previousReading"
                      :min="0"
                      :precision="2"
                      :step="0.01"
                      placeholder="上次读数"
                      size="small"
                      style="width: 100%"
                      disabled
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="usage" label="用量" width="100">
                  <template #default="{ row }">
                    <span>{{ calculateUsage(row) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="120">
                  <template #default="{ row }">
                    <el-input
                      v-model="row.remark"
                      placeholder="备注"
                      size="small"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          确认提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { MeterReading } from '../types/property'
import { meterReadingApi } from '@/api/property'
import { buildingApi } from '@/api/building'
import { householdApi } from '@/api/household'
import { regionApi } from '@/api/region'
import { showError, showWarning } from '@/utils/message'

// Props
interface Props {
  modelValue: boolean
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [data: any]
}>()

// 响应式数据
const singleFormRef = ref<FormInstance>()
const batchFormRef = ref<FormInstance>()
const inputMethod = ref<'SINGLE' | 'BATCH'>('SINGLE')
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const householdList = ref<any[]>([])

// 单个录入表单
const singleForm = reactive({
  communityId: 0,
  buildingId: 0,
  householdId: 0,
  meterType: 'WATER' as 'WATER' | 'ELECTRICITY' | 'GAS',
  meterNumber: '',
  currentReading: 0,
  previousReading: 0,
  usage: 0,
  readingDate: '',
  remark: ''
})

// 批量录入表单
const batchForm = reactive({
  communityId: 0,
  meterType: 'WATER' as 'WATER' | 'ELECTRICITY' | 'GAS',
  readingDate: '',
  readings: [] as Array<{
    householdId: number
    roomNumber: string
    householdName: string
    meterNumber: string
    currentReading: number
    previousReading: number
    usage: number
    remark: string
  }>
})

// 表单验证规则
const singleRules: FormRules = {
  communityId: [
    { required: true, message: '请选择社区', trigger: 'change' }
  ],
  buildingId: [
    { required: true, message: '请选择楼栋', trigger: 'change' }
  ],
  householdId: [
    { required: true, message: '请选择房户', trigger: 'change' }
  ],
  meterType: [
    { required: true, message: '请选择表类型', trigger: 'change' }
  ],
  meterNumber: [
    { required: true, message: '请输入表号', trigger: 'blur' }
  ],
  currentReading: [
    { required: true, message: '请输入本次读数', trigger: 'blur' }
  ],
  readingDate: [
    { required: true, message: '请选择读数日期', trigger: 'change' }
  ]
}

const batchRules: FormRules = {
  communityId: [
    { required: true, message: '请选择社区', trigger: 'change' }
  ],
  meterType: [
    { required: true, message: '请选择表类型', trigger: 'change' }
  ],
  readingDate: [
    { required: true, message: '请选择读数日期', trigger: 'change' }
  ],
  readings: [
    { required: true, message: '请加载房户列表', trigger: 'change' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听器
watch(() => singleForm.currentReading, (newVal) => {
  if (newVal && singleForm.previousReading) {
    singleForm.usage = newVal - singleForm.previousReading
  }
})

// 生命周期
const loadCommunityList = async () => {
  try {
    const response = await regionApi.getCommunityList()
    if (response.success) {
      communityList.value = response.data
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    showError('加载社区列表失败')
  }
}

const loadBuildingList = async (communityId: number) => {
  try {
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    if (response.data) {
      buildingList.value = response.data
    }
  } catch (error) {
    console.error('加载楼栋列表失败:', error)
    showError('加载楼栋列表失败')
  }
}

const loadHouseholdList = async () => {
  if (!batchForm.communityId) {
    showWarning('请先选择社区')
    return
  }

  try {
    const response = await householdApi.getHouseholdList({ communityId: batchForm.communityId })
    if (response.data) {
      batchForm.readings = response.data.map((household: any) => ({
        householdId: household.id,
        roomNumber: household.roomNumber,
        householdName: household.ownerName,
        meterNumber: '',
        currentReading: 0,
        previousReading: 0,
        usage: 0,
        remark: ''
      }))
    }
  } catch (error) {
    console.error('加载房户列表失败:', error)
    showError('加载房户列表失败')
  }
}

// 事件处理
const handleInputMethodChange = () => {
  // 重置表单
  if (singleFormRef.value) {
    singleFormRef.value.resetFields()
  }
  if (batchFormRef.value) {
    batchFormRef.value.resetFields()
  }
  batchForm.readings = []
}

const handleCommunityChange = () => {
  singleForm.buildingId = 0
  singleForm.householdId = 0
  buildingList.value = []
  householdList.value = []
  if (singleForm.communityId) {
    loadBuildingList(singleForm.communityId)
  }
}

const handleBuildingChange = () => {
  singleForm.householdId = 0
  householdList.value = []
  if (singleForm.buildingId) {
    loadHouseholdListByBuilding(singleForm.buildingId)
  }
}

const handleHouseholdChange = () => {
  if (singleForm.householdId) {
    loadMeterHistory(singleForm.householdId, singleForm.meterType)
  }
}

const handleBatchCommunityChange = () => {
  batchForm.readings = []
}

const loadHouseholdListByBuilding = async (buildingId: number) => {
  try {
    const response = await householdApi.getHouseholdList({ buildingId })
    if (response.data) {
      householdList.value = response.data
    }
  } catch (error) {
    console.error('加载房户列表失败:', error)
    showError('加载房户列表失败')
  }
}

const loadMeterHistory = async (householdId: number, meterType: string) => {
  try {
    const response = await meterReadingApi.getHouseholdMeterHistory(householdId, meterType)
    if (response.success && response.data.length > 0) {
      const lastReading = response.data[response.data.length - 1]
      singleForm.previousReading = lastReading.currentReading
      singleForm.meterNumber = lastReading.meterNumber
    }
  } catch (error) {
    console.error('加载表读数历史失败:', error)
  }
}

const calculateUsage = (row: any) => {
  if (row.currentReading && row.previousReading) {
    return (row.currentReading - row.previousReading).toFixed(2)
  }
  return '0.00'
}

const handleSubmit = async () => {
  if (inputMethod.value === 'SINGLE') {
    await handleSingleSubmit()
  } else {
    await handleBatchSubmit()
  }
}

const handleSingleSubmit = async () => {
  if (!singleFormRef.value) return

  try {
    await singleFormRef.value.validate()
    
    const submitData = {
      householdId: singleForm.householdId,
      meterNumber: singleForm.meterNumber,
      meterType: singleForm.meterType,
      currentReading: singleForm.currentReading,
      readingDate: singleForm.readingDate,
      readerName: '系统录入',
      remark: singleForm.remark
    }

    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleBatchSubmit = async () => {
  if (!batchFormRef.value) return

  try {
    await batchFormRef.value.validate()
    
    const validReadings = batchForm.readings.filter(reading => 
      reading.meterNumber && reading.currentReading > 0
    )

    if (validReadings.length === 0) {
      showWarning('请至少录入一条有效的表读数')
      return
    }

    const submitData = {
      readings: validReadings.map(reading => ({
        householdId: reading.householdId,
        meterNumber: reading.meterNumber,
        meterType: batchForm.meterType,
        currentReading: reading.currentReading,
        readingDate: batchForm.readingDate,
        readerName: '系统录入',
        remark: reading.remark
      }))
    }

    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  if (singleFormRef.value) {
    singleFormRef.value.resetFields()
  }
  if (batchFormRef.value) {
    batchFormRef.value.resetFields()
  }
  
  Object.assign(singleForm, {
    communityId: 0,
    buildingId: 0,
    householdId: 0,
    meterType: 'WATER',
    meterNumber: '',
    currentReading: 0,
    previousReading: 0,
    usage: 0,
    readingDate: '',
    remark: ''
  })
  
  Object.assign(batchForm, {
    communityId: 0,
    meterType: 'WATER',
    readingDate: '',
    readings: []
  })
  
  inputMethod.value = 'SINGLE'
}

// 初始化
loadCommunityList()
</script>

<style scoped>
.meter-reading-content {
  max-height: 600px;
  overflow-y: auto;
}

.input-method-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.single-input,
.batch-input {
  margin-bottom: 20px;
}

.batch-data-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px;
}

.batch-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
  color: #303133;
}

.dialog-footer {
  text-align: right;
}
</style> 